//
//  CreateJobSystemDetailView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/3.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
class CreateJobSystemDetailView: CreateJobBaseView {
    //panel inverter battery合并在一起的View
    let gridConnectedView = GridConnectedView()
    let installationTypeView = InstallationTypeView()
    let combineView = SystemInfoCombineView()
    let isOptimizereeInstalledSwitchView = SwitchButtonWithTitle(title: R.string.localizable.willThereBeAnyOptimisersInstalled(),hasBorder: false)
    override func setUpContentView() {
        //grid connected
        self.contentView.addSubview(gridConnectedView)
        gridConnectedView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //installation type
        self.contentView.addSubview(installationTypeView)
        installationTypeView.snp.makeConstraints { make in
            make.top.equalTo(gridConnectedView.snp.bottom).offset(Constant.SectionTopMargin)
            make.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        //panel, inverter, batterys
        self.contentView.addSubview(combineView)
        combineView.snp.makeConstraints { make in
            make.top.equalTo(installationTypeView.snp.bottom)
            make.right.left.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //isOptimizereeInstalledSwitchView
        self.contentView.addSubview(isOptimizereeInstalledSwitchView)
        isOptimizereeInstalledSwitchView.snp.makeConstraints { make in
            make.top.equalTo(combineView.snp.bottom)
            make.left.right.equalTo(installationTypeView)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-Constant.AllOutMargin)
        }
        //
        self.combineView.scrollToViewClosure = { [weak self] type in
            guard let strongSelf = self else {return}
            strongSelf.layoutIfNeeded()
            //跳转到scan部分
            if type == .Panel{
                let recOnTableView = strongSelf.combineView.panelTableView.rectForRow(at: IndexPath(row: strongSelf.combineView.panelTableView.list.count - 1, section: 0))
                let pointOnScrollView = strongSelf.combineView.panelTableView.convert(recOnTableView.origin, to: strongSelf.scrollView)
                strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
            }else if type == .Inverter{
                let recOnTableView = strongSelf.combineView.inverterTableView.rectForRow(at: IndexPath(row: strongSelf.combineView.inverterTableView.list.count - 1, section: 0))
                let pointOnScrollView = strongSelf.combineView.inverterTableView.convert(recOnTableView.origin, to: strongSelf.scrollView)
                strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
            }else if type == .Battery{
                let recOnTableView = strongSelf.combineView.batteryCommonView.tableView.rectForRow(at: IndexPath(row: strongSelf.combineView.batteryCommonView.list.count - 1, section: 0))
                let pointOnScrollView = strongSelf.combineView.batteryCommonView.tableView.convert(recOnTableView.origin, to: strongSelf.scrollView)
                strongSelf.scrollView.scrollToView(point: pointOnScrollView, animated: true)
            }
            
        }
    }
    func setData(_ model: SystemDetailViewModel){
        //
        let installationTypeViewModel = InstallationTypeViewModel()
        installationTypeViewModel.installation_type = model.installation_type
        installationTypeViewModel.additional_upgrade_system_details = model.additional_capacity_details
        self.installationTypeView.setData(installationTypeViewModel,editFlag: false)
        self.combineView.loadData(isBattery: model.is_battery,panels: model.panels, inverters: model.inverters, batteries: model.batteries)
        //view Model
        let gridViewModel = GridConnectedViewModel()
        gridViewModel.connected_type = model.connected_type
        gridViewModel.nmi = model.nmi
        gridViewModel.isNMIRequired = false//创建job NMI是非必填的
        gridViewModel.gridConnectionApplicationRefNo = model.gridConnectionApplicationRefNo
        self.gridConnectedView.setData(gridViewModel)
        self.isOptimizereeInstalledSwitchView.switchBtn.switchOn(model.installed_optimiser)
        //
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.installation type
        //1.installation type
        let newOrReplacementValid = self.installationTypeView.viewModel.rx.observe(String.self, "installation_type_value").map({
            let data = $0 ?? ""
            if data != "" {
                if $0 == InstallationTypeValue.New.rawValue || $0 == InstallationTypeValue.Replacement.rawValue{
                    return true
                }else{
                    return false
                }
            }else{
                return false
            }
            
        }).share(replay: 1)
        //2.additianal details
        let additionalForOtherValid = self.installationTypeView.viewModel.rx.observe(String.self, "additional_upgrade_system_details").map({
            if Tool().isValidAddtionalInfo(($0 ?? "")){
                return true
            }else{
                return false
            }
        }).share(replay: 1)
        //3.0additianal details is empty
        let additionalForNewOrReplacementValid = self.installationTypeView.viewModel.rx.observe(String.self, "additional_upgrade_system_details").map({
            let text = ($0 ?? "")
            if text == ""{
                return true
            }else{
                if Tool().isValidAddtionalInfo(text){
                    return true
                }else{
                    return false
                }
            }
        }).share(replay: 1)
        let installationTypeInfoValid = Observable.combineLatest(
            newOrReplacementValid,
            additionalForOtherValid,
            additionalForNewOrReplacementValid
        ) {
            if ($0 && $2) || (!$0 && $1) {
                return true
            }
            return false
        }
        .share(replay: 1)
        //2.panels
        let panelsValid = self.combineView.panelTableView.rx.observe(Array<InstallationDetailSystemDetailForPanelModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { panelModel in
                    if panelModel.model == "" || panelModel.watts_per_panel == 0 || panelModel.number_panels == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        //3.inverter
        let inverersValid = self.combineView.inverterTableView.rx.observe(Array<InstallationDetailSystemDetailForInverterModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { inverterModel in
                    if inverterModel.inverter_model == "" || inverterModel.number_inverters == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        
        //4.battery
        let isBatteryValid = self.combineView.batteryCommonView.isBattery.map({$0}).share(replay: 1)
        let batteriesValid = self.combineView.batteryCommonView.rx.observe(Array<InstallationDetailSystemDetailForBatteryModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { batteryModel in
                    if batteryModel.battery_model == "" || batteryModel.number_batteries == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        //整个battery 信息是否有效
        let batteryInfoValid = Observable.combineLatest(
            isBatteryValid,
            batteriesValid
          ) { !$0 || ($0 && $1)}
          .share(replay: 1)
        //5.grid connected
        let isGridConnectedValid = self.gridConnectedView.viewModel.rx.observe(String.self, "connected_type_value").map({
            let data = $0 ?? ""
            if data == GridConnectedValue.onGrid.rawValue {
                return true
            }else{
                return false
            }
        }).share(replay: 1)
        //
        let nmiValid = self.gridConnectedView.viewModel.rx.observe(String.self, "nmi").map({
            let data = ($0 ?? "").trimmingCharacters(in: .whitespaces)
            if self.gridConnectedView.viewModel.isNMIRequired && data.count == 0 {
                return false
            }
            return true
        }).share(replay: 1)
        //整个installationType 信息是否有效
        let gridConnectInfoValid = Observable.combineLatest(
            isGridConnectedValid,
            nmiValid
          ) { !$0 || ($0 && $1)}
          .share(replay: 1)
        //6.合并
        let everythingValid = Observable.combineLatest(
            installationTypeInfoValid,
            panelsValid,
            inverersValid,
            batteryInfoValid,
            gridConnectInfoValid
          ) {
              if $0 && $1 && $2 && $3 && $4{
                  return true
              }
              return false
          }
          .share(replay: 1)
        //
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.continueBtn.enableBtn()
            }else{
                strongSelf.continueBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    //MARK: - 滚动到无效的行
    fileprivate func scrollToInvalidRow(panelRow: Int? = nil , inverterRow: Int? = nil, batteryRow: Int? = nil){
        if let row = panelRow {//panel 没有检验通过的第一行
            let cellFame = self.combineView.panelTableView.rectForRow(at: IndexPath(row: row, section: 0))
            let offsetY = self.scrollView.convert(cellFame, from: self.combineView.panelTableView).origin.y
            self.scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        }else if let row = inverterRow  {//inverter 没有检验通过的第一行
            let cellFame = self.combineView.inverterTableView.rectForRow(at: IndexPath(row: row, section: 0))
            let offsetY = self.scrollView.convert(cellFame, from: self.combineView.inverterTableView).origin.y
            self.scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        }else if let row = batteryRow  {//battery 没有检验通过的第一行
            //cell在tableview上的frame
            let cellFame = self.combineView.batteryCommonView.tableView.rectForRow(at: IndexPath(row: row, section: 0))
            //cell转换在batteryCommonView的frame
            let cellOnCommonViewFrame = self.combineView.batteryCommonView.convert(cellFame, from: self.combineView.batteryCommonView.tableView)
            //cell转换在scrollView的frame
            let offsetY = self.scrollView.convert(cellOnCommonViewFrame, from: self.combineView.batteryCommonView).origin.y
            self.scrollView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        }
    }
}
